var events = require('events');
var net = require('net');

var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};

channel.on('join',function(id,client){
    console.log("join id="+id+",client="+client);
    this.clients[id] = client;
    this.subscriptions[id] = function(senderId,message){
        console.log("broadcast id=" + id + ",client=" + client);
        if(id!=senderId){
            this.clients[id].write(message);
        }
    };
    this.on('broadcast',this.subscriptions[id]);
});

channel.on('leave',function(id){
    channel.removeListener('broadcast',this.subscriptions[id]);
    channel.emit('broadcast',id,id+' has left thechat.\n');
});



var server = net.createServer(function(client){
    
});
server.on('connection',function(client){
    var id = client.remoteAddress + ':' + client.remotePort;
    console.log("id = " + id + ",client=" + client);
    channel.emit('join', id, client);
    // client.on('connect',function(){
    //     console.log('connect');

    // });
    client.on('data', function (data) {
        console.log('data');
        data = data.toString();
        channel.emit('broadcast', id, data);
    });

    client.on('close', function () {
        console.log("close");
        channel.emit('leave',id);
    });
    console.log('connected');
});
server.listen(8888);